#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time        : 2021/10/12 18:54
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : dcm_enhance.py
@Version     : Version 1.0.0
@Description : TODO
@Created By  : PyCharm
"""
import pydicom
from DIP_experiment_4.util import contrast_show
import numpy as np
from matplotlib import pyplot as plt

im = pydicom.dcmread("../experiment_fig/I1700000")
my_font = "C:/Windows/Fonts/simsun.ttc"
win_width = im.WindowWidth
win_center = im.WindowCenter
# CT值开窗
ct_a = win_center - win_width / 2  # 0
ct_b = win_center + win_width / 2  # 90
ct_min, ct_max = -1024, 3071
ct_k = (ct_max - ct_min) / (ct_b - ct_a)
pixel_array = im.pixel_array
CT_value = im.RescaleSlope * pixel_array + im.RescaleIntercept
my_im1 = np.piecewise(CT_value, [CT_value < ct_a, CT_value > ct_b],
                      [ct_min, ct_max, lambda CT_value: ct_k * CT_value - 1024])
# 灰度值开窗
gray_a = (ct_a - im.RescaleIntercept) / im.RescaleSlope
gray_b = (ct_b - im.RescaleIntercept) / im.RescaleSlope
gray_min = 0
gray_max = 255
gray_k = (gray_max - gray_min) / (gray_b - gray_a)
my_im2 = np.piecewise(pixel_array, [pixel_array < gray_a, pixel_array > gray_b],
                      [gray_min, gray_max, lambda pixel_array: gray_k * pixel_array - 2901.33])

# 保存为jpg
plt.imsave("../experiment_fig/I1700000_CT.jpg", my_im1, cmap="gray")
plt.imsave("../experiment_fig/I1700000_gray.jpg", my_im2, cmap="gray")
# 显示图像
im_dict = {"原始图像": pixel_array, "CT值开窗": my_im1, "灰度值开窗": my_im2}
contrast_show(im_dict, (1, 3), font=my_font)
